
class ScoreInfo:
    # 学生编号 id_no,姓名 name,课程 course,成绩 score,班级 cls,年度 year
    def __init__(self, **kwargs):
        print("------------------初始化 ScoreInfo-----------")
        self.id_no = kwargs.get("id_no")
        self.name = kwargs.get("name")
        self.course = kwargs.get("course")
        self.score = kwargs.get("score")
        self.cls = kwargs.get("cls")
        self.year = kwargs.get("year")

    '''把对象字典转换成csv行字符串:9001,张飞,语言,90,科创一班,2022'''
    @classmethod
    def dict_to_csv_row(cls, dict_obj):
        return f"{dict_obj['id_no']},{dict_obj['name']},{dict_obj['course']},{dict_obj['score']},{dict_obj['cls']},{dict_obj['year']}\n"

    '''文件读取csv内容，转换字典列表'''
    @classmethod
    def read_score_data(cls):
        with open("score_data.csv", "r", encoding="utf-8") as f:
            lines = f.readlines()
            score_data = []
            for line in lines:
                cols = line.strip().split(",")
                #转换成对象
                score_info = ScoreInfo(id_no=int(cols[0]), name=cols[1], course=cols[2], score=int(cols[3]), cls=cols[4], year=int(cols[5]))
                score_data.append(score_info.__dict__)
            return score_data



    '''写入csv文件,内存数据写入文件'''
    @classmethod
    def write_score_data(cls, data):
        # 写入文件
        with open("score_data.csv", "w", encoding="utf-8") as f:
            for item in data:
                #转换成csv格式，写入文件
                f.write(cls.dict_to_csv_row(item))






'''测试代码'''
if __name__ == "__main__":
    score_info = ScoreInfo(id_no=9001, name="张飞", course="语言", score=90, cls="科创一班", year=2022)
    print(score_info)
    print(score_info.dict_to_csv_row(score_info.__dict__))